package com.fawkes.project.example.common.config;

import com.fawkes.secure.data.interceptor.PrepareInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.annotation.Resource;
import javax.sql.DataSource;

/**
 * 数据源配置
 *
 * @author zhang_ht2
 * @date 2020/08/05
 */
@Configuration
@MapperScan(basePackages = {"com.fawkes.project.example.common.mapper"}, sqlSessionFactoryRef = "fawkesDataSourceFactory")
public class FawkesDataSourceConfig {
    @Resource
    private PrepareInterceptor prepareInterceptor;
    /**
     * 源
     */
    @Bean(name = "fawkesDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.fawkes")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 工厂
     */
    @Bean("fawkesDataSourceFactory")
    @Primary
    @DependsOn("fawkesDataSource")
    public SqlSessionFactory dataSourceFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        factoryBean.setPlugins(new Interceptor[]{prepareInterceptor});
        return factoryBean.getObject();
    }


    /**
     * 模板
     */
    @Bean("fawkesSqlSessionTemplate")
    @Primary
    @DependsOn("fawkesDataSourceFactory")
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("fawkesDataSourceFactory") SqlSessionFactory sessionfactory) {
        return new SqlSessionTemplate(sessionfactory);
    }


    /**
     * 事务
     */
    @Bean(name = "fawkesTransactionManager")
    @Primary
    @DependsOn("fawkesDataSource")
    public DataSourceTransactionManager fawkesTransactionManager(@Qualifier("fawkesDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
